﻿using AutoMapper;
using QYmall.Core.Common.Emum;
using QYmall.Core.Common.Extensions;
using QYmall.Core.Common.Helper;
using QYmall.Core.DBFactory.Database;
using QYmall.Core.IServices;
using QYmall.Core.Model.Models;
using QYmall.Core.Model.ViewModels;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace QYmall.Core.Services
{
    /// <summary>
    /// 订单接口实现
    /// </summary>
    public class OrderService : BaseService, IOrderService
    {
        private readonly IUserService _userService;
        private readonly ISysConfigService _configService;
        private readonly IMapper _mapper;

        public OrderService(IDbContextFactory contentFactory,
            IUserService userService, ISysConfigService configService, IMapper mapper) : base(contentFactory)
        {
            _userService = userService;
            _configService = configService;
            _mapper = mapper;
        }

        /// <summary>
        /// 查询一条记录
        /// </summary>
        public async Task<Orders?> QueryAsync(Expression<Func<Orders, bool>> funcWhere, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            var result = await _context.Set<Orders>()
                .Include(x => x.Merchant)
                .Include(x => x.Delivery)
                .Include(x => x.OrderGoods)
                .Include(x => x.OrderLog)
                .Include(x => x.OrderPromotion).ThenInclude(x => x.Promotion)
                .Include(x => x.CollectionRelations).ThenInclude(x => x.Collection)
                .FirstOrDefaultAsync(funcWhere);
            return result;
        }

        /// <summary>
        /// 查询一条订单货品记录
        /// </summary>
        public async Task<OrderGoods?> QueryGoodsAsync(Expression<Func<OrderGoods, bool>> funcWhere, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            var result = await _context.Set<OrderGoods>()
                .Include(x => x.Order) .FirstOrDefaultAsync(funcWhere);
            return result;
        }

        /// <summary>
        /// 查询指定数量列表
        /// </summary>
        public async Task<IEnumerable<Orders>> QueryListAsync(int top, Expression<Func<Orders, bool>> funcWhere,
            string orderBy, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            var result = _context.Set<Orders>()
                .Include(x => x.Merchant)
                .Include(x => x.Delivery)
                .Include(x => x.OrderGoods)
                .Include(x => x.CollectionRelations).ThenInclude(x => x.Collection)
                .Where(funcWhere).OrderByBatch(orderBy);//调用Linq扩展类进行排序
            if (top > 0) result = result.Take(top);//等于0显示所有数据
            return await result.ToListAsync();
        }

        /// <summary>
        /// 查询分页列表
        /// </summary>
        public async Task<PaginationList<Orders>> QueryPageAsync(int pageSize, int pageIndex, Expression<Func<Orders, bool>> funcWhere,
            string orderBy, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            var result = _context.Set<Orders>()
                .Include(x => x.Merchant)
                .Include(x => x.Delivery)
                .Include(x => x.OrderGoods)
                .Include(x => x.CollectionRelations).ThenInclude(x => x.Collection)
                .Where(funcWhere).OrderByBatch(orderBy);//调用Linq扩展类排序
            return await PaginationList<Orders>.CreateAsync(pageIndex, pageSize, result);
        }

        /// <summary>
        /// 获取订单总数量
        /// </summary>
        public async Task<int> QueryCountAsync(Expression<Func<Orders, bool>> funcWhere, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            return await _context.Set<Orders>().Where(funcWhere).CountAsync();
        }

        /// <summary>
        /// 获取订单总金额
        /// </summary>
        public async Task<decimal> QueryAmountAsync(Expression<Func<Orders, bool>> funcWhere, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            var result = await _context.Set<Orders>()
                .Where(funcWhere).OrderByDescending(x => x.AddTime)
                .GroupBy(x => new { x.AddTime.Month, x.AddTime.Day })
                .Select(g => g.Sum(x => x.OrderAmount)).FirstOrDefaultAsync();
            return result;
        }

        /// <summary>
        /// 添加订单
        /// </summary>
        public async Task<OrderCollectionDto?> AddAsync(OrdersAddDto modelDto, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            //映射DTO到实体
            OrderCollection? result;
            //检查订单列表
            if (modelDto.OrderList.Count == 0)
            {
                throw new ResponseException("没有需要结算的订单，请确认后操作");
            }

            //判断订单类型1定时抢购
            if (modelDto.OrderType == 1)
            {
                result = await AddRushOrder(modelDto);
            }
            //2预售订单
            else if (modelDto.OrderType == 2)
            {
                result = await AddPresellOrder(modelDto);
            }
            //3积分换购
            else if (modelDto.OrderType == 3)
            {
                result = await AddPointOrder(modelDto);
            }
            //0普通订单
            else
            {
                result = await AddNormalOrder(modelDto);
            }
            //映射成DTO
            return _mapper.Map<OrderCollectionDto>(result);
        }

        /// <summary>
        /// 修改一条记录
        /// </summary>
        public async Task<bool> UpdateAsync(Expression<Func<Orders, bool>> funcWhere, OrdersEditDto modelDto, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            //根据ID获取记录
            var model = await _context.Set<Orders>().FirstOrDefaultAsync(funcWhere);
            //如果不存在则抛出异常
            if (model == null)
            {
                throw new ResponseException("数据不存在或已删除", ErrorCode.NotFound);
            }
            //未发货
            if (model.DeliveryStatus == 0)
            {
                model.Province = modelDto.Province;
                model.City = modelDto.City;
                model.Area = modelDto.Area;
                var addressArr = modelDto.Address?.Split(",");
                if(addressArr?.Length > 0)
                {
                    model.Address = $"{model.Province},{model.City},{model.Area},{addressArr[^1]}";
                }
                model.AcceptName = modelDto.AcceptName;
                model.TelPhone = modelDto.TelPhone;
                model.Mobile = modelDto.Mobile;
                model.Postscript = modelDto.Postscript;
                model.AcceptTime = modelDto.AcceptTime;
            }
            model.Remark = modelDto.Remark;
            //新增订单日志
            await _context.Set<OrderLog>().AddAsync(new OrderLog
            {
                OrderId = model.Id,
                OrderNo = model.OrderNo,
                ActionType = ActionType.Edit.ToString(),
                AddBy = await _userService.GetUserNameAsync(),
                AddTime = DateTime.Now,
                Remark = $"订单[{model.OrderNo}]修改"
            });
            //保存到数据库
            _context.Set<Orders>().Update(model);
            return await this.SaveAsync();
        }

        /// <summary>
        /// 签收订单(管理员)
        /// </summary>
        public async Task<bool> ReceiptAsync(Expression<Func<Orders, bool>> funcWhere, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            //根据ID获取记录
            var model = await _context.Set<Orders>()
                .Include(x => x.CollectionRelations).ThenInclude(x => x.Collection)
                .FirstOrDefaultAsync(funcWhere);
            //如果不存在则抛出异常
            if (model == null)
            {
                throw new ResponseException("订单不存在或已删除");
            }
            if (model.Status > 3)
            {
                throw new ResponseException("订单未发货，无法签收操作");
            }
            //检查支付状态，如果是未付款，则检查是否到付
            if (model.PaymentStatus != 2)
            {
                foreach (var relation in model.CollectionRelations)
                {
                    if (relation.Collection == null)
                    {
                        throw new ResponseException("找不到收款记录，无法操作");
                    }
                    if (relation.Collection.PaymentCash == 0 && relation.Collection.Status != 2)
                    {
                        throw new ResponseException("订单未付款，无法操作");
                    }
                    //货到付款，则修改成已支付
                    if (relation.Collection.PaymentCash == 1)
                    {
                        relation.Collection.Status = 2;
                        relation.Collection.CompleteTime = DateTime.Now;
                    }
                }
                //付款没问题后设置订单付款状态为全部支付
                model.PaymentStatus = 2;
            }
            //新增订单日志
            await _context.Set<OrderLog>().AddAsync(new OrderLog
            {
                OrderId = model.Id,
                OrderNo = model.OrderNo,
                ActionType = ActionType.Accept.ToString(),
                AddBy = await _userService.GetUserNameAsync(),
                AddTime = DateTime.Now,
                Remark = $"订单[{model.OrderNo}]签收完成"
            });

            //更改订单为已签收状态
            model.Status = 4;
            _context.Set<Orders>().Update(model);

            return await this.SaveAsync();
        }

        /// <summary>
        /// 完成订单(管理员)
        /// </summary>
        public async Task<bool> CompleteAsync(Expression<Func<Orders, bool>> funcWhere, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            return await CompleteOrderAsync(funcWhere);
        }

        /// <summary>
        /// 作废订单(管理员)
        /// </summary>
        public async Task<bool> InvalidAsync(Expression<Func<Orders, bool>> funcWhere, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            //根据ID获取记录
            var model = await _context.Set<Orders>()
                .Include(x => x.OrderGoods)
                .FirstOrDefaultAsync(funcWhere);
            //如果不存在则抛出异常
            if (model == null)
            {
                throw new ResponseException("订单不存在或已删除");
            }
            //新增订单日志
            await _context.Set<OrderLog>().AddAsync(new OrderLog
            {
                OrderId = model.Id,
                OrderNo = model.OrderNo,
                ActionType = ActionType.Invalid.ToString(),
                AddBy = await _userService.GetUserNameAsync(),
                AddTime = DateTime.Now,
                Remark = $"订单[{model.OrderNo}]作废"
            });
            //返还库存处理
            var productIds = model.OrderGoods.Select(x => x.ProductId);//货品列表
            var productList = await _context.Set<ShopGoodsProduct>()
                .Include(x => x.ShopGoods)
                .Where(x => x.ShopGoods!.Status == 0 && productIds.Contains(x.Id)).ToListAsync();
            foreach (var modelt in productList)
            {
                if (modelt.ShopGoods == null)
                {
                    continue;
                }
                //取得货品的购买数量
                var orderGoods = model.OrderGoods.FirstOrDefault(x => x.ProductId == modelt.Id);
                if(orderGoods != null)
                {
                    //货品及商品减库存，销售减少
                    modelt.StockQuantity += orderGoods.Quantity;
                    modelt.ShopGoods.StockQuantity += orderGoods.Quantity;
                    modelt.ShopGoods.SaleCount = modelt.ShopGoods.SaleCount - orderGoods.Quantity;
                    _context.Set<ShopGoodsProduct>().Update(modelt);
                }
            }
            //修改订单状态
            model.Status = 7;
            _context.Set<Orders>().Update(model);

            return await this.SaveAsync();
        }

        /// <summary>
        /// 取消订单(客户)
        /// </summary>
        public async Task<bool> CancelAsync(long id, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            //获取当前登录用户
            var userId = await _userService.GetUserIdAsync();
            if (await _context.Set<Members>().FirstOrDefaultAsync(x => x.UserId == userId) == null)
            {
                throw new ResponseException("会员未登录或已超时", ErrorCode.TokenExpired, StatusCodes.Status401Unauthorized);
            }
            //根据ID获取订单记录
            var model = await _context.Set<Orders>().FirstOrDefaultAsync(x => x.Id == id && x.UserId == userId);
            //如果不存在则抛出异常
            if (model == null)
            {
                throw new ResponseException("订单不存在或已删除", ErrorCode.NotFound, StatusCodes.Status404NotFound);
            }
            if (model.PaymentStatus > 0)
            {
                throw new ResponseException("订单已支付，无法取消");
            }
            //新增订单日志
            await _context.Set<OrderLog>().AddAsync(new OrderLog
            {
                OrderId = model.Id,
                OrderNo = model.OrderNo,
                ActionType = ActionType.Invalid.ToString(),
                AddBy = await _userService.GetUserNameAsync(),
                AddTime = DateTime.Now,
                Remark = $"订单[{model.OrderNo}]取消"
            });
            //返还库存处理
            var productIds = model.OrderGoods.Select(x => x.ProductId);//货品列表
            var productList = await _context.Set<ShopGoodsProduct>()
                .Include(x => x.ShopGoods)
                .Where(x => x.ShopGoods!.Status == 0 && productIds.Contains(x.Id)).ToListAsync();
            foreach (var modelt in productList)
            {
                if (modelt.ShopGoods == null)
                {
                    continue;
                }
                //取得货品的购买数量
                var orderGoods = model.OrderGoods.FirstOrDefault(x => x.ProductId == modelt.Id);
                if (orderGoods != null)
                {
                    //货品及商品减库存，销售增加
                    modelt.StockQuantity += orderGoods.Quantity;
                    modelt.ShopGoods.StockQuantity += orderGoods.Quantity;
                    modelt.ShopGoods.SaleCount = modelt.ShopGoods.SaleCount - orderGoods.Quantity;
                    _context.Set<ShopGoodsProduct>().Update(modelt);
                }
            }
            //修改订单状态
            model.Status = 6;
            _context.Set<Orders>().Update(model);

            return await this.SaveAsync();
        }

        /// <summary>
        /// 确认收货(客户)
        /// </summary>
        public async Task<bool> ConfirmAsync(long id, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            //获取当前登录用户
            var userId = await _userService.GetUserIdAsync();
            if(await _context.Set<Members>().FirstOrDefaultAsync(x => x.UserId == userId) == null)
            {
                throw new ResponseException("会员未登录或已超时");
            }
            return await CompleteOrderAsync(x => x.Id == id && (userId <= 0 || x.UserId == userId));
        }

        /// <summary>
        /// 根据条件删除记录
        /// </summary>
        public async Task<bool> DeleteAsync(Expression<Func<Orders, bool>> funcWhere, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            var list = await _context.Set<Orders>()
                .Include(x=>x.OrderLog)
                .Include(x=>x.CollectionRelations)
                .Include(x => x.OrderGoods).Where(funcWhere).ToListAsync();
            if (list == null)
            {
                return false;
            }
            foreach (var modelt in list)
            {
                _context.Set<Orders>().Attach(modelt);
            }
            _context.Set<Orders>().RemoveRange(list);
            return await this.SaveAsync();
        }

        /// <summary>
        /// 完成订单(计划任务)
        /// </summary>
        public async Task JobCompleteAsync(WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            //获取订单配置信息
            var jsonData = await _configService.QueryByTypeAsync(ConfigType.OrderConfig);
            var orderConfig = JsonHelper.ToJson<OrderConfigDto>(jsonData?.JsonData);
            if (orderConfig == null)
            {
                return;
            }
            //检查已发货或已签收的订单，必须到达自动确认期的订单
            var list = await _context.Set<Orders>()
                .Include(x => x.CollectionRelations).ThenInclude(x => x.Collection)
                .Where(x => (x.Status == 3 || x.Status == 4) 
                && x.DeliveryTime != null
                && DateTime.Compare(x.DeliveryTime.Value, DateTime.Now.AddDays(-1 * orderConfig.OrdereComplete)) <= 0)
                .ToListAsync();
            if (list == null || list.Count == 0)
            {
                return;
            }
            //循环处理
            foreach (var model in list)
            {
                //检查支付状态，如果是未付款，则检查是否到付
                if (model.PaymentStatus != 2)
                {
                    foreach (var relation in model.CollectionRelations)
                    {
                        //货到付款，则修改成已支付
                        if (relation.Collection != null && relation.Collection.PaymentCash == 1)
                        {
                            relation.Collection.Status = 2;
                            relation.Collection.CompleteTime = DateTime.Now;
                        }
                    }
                    //付款没问题后设置订单付款状态为全部支付
                    model.PaymentStatus = 2;
                }
                //检查订单促销活动
                if (model.OrderType == 0 && model.ActiveId > 0)
                {
                    //查询促销活动详情
                    var promotionModel = await _context.Set<ShopPromotion>().FirstOrDefaultAsync(x => x.Id == model.ActiveId);
                    //赠送优惠券
                    if (promotionModel != null && promotionModel.AwardType == 4)
                    {
                        if (await _context.Set<ShopCoupon>().FirstOrDefaultAsync(x => x.Id == promotionModel.AwardValue) != null)
                        {
                            await _context.Set<ShopCouponHistory>().AddAsync(new ShopCouponHistory()
                            {
                                CouponId = promotionModel.AwardValue,
                                UserId = model.UserId,
                                UserName = model.UserName,
                                Type = 0,
                                IsUse = 0,
                                Status = 0,
                                AddTime = DateTime.Now
                            });
                        }
                    }
                }
                //会员增加积分及经验值
                if (model.Point > 0)
                {
                    var memberModel = await _context.Set<Members>().Include(x => x.Group).FirstOrDefaultAsync(x => x.UserId == model.UserId);
                    if (memberModel != null)
                    {
                        memberModel.Point += model.Point;
                        memberModel.Exp += model.Exp;
                        //检查有无可升级的会员组
                        var upgradeGroupModel = await _context.Set<MemberGroup>().FirstOrDefaultAsync(
                            x => x.Id != memberModel.GroupId
                            && x.IsUpgrade == 1
                            && x.MinExp <= memberModel.Exp
                            && x.MaxExp >= memberModel.Exp);
                        if (upgradeGroupModel != null && upgradeGroupModel.Amount >= memberModel.Group?.Amount)
                        {
                            memberModel.GroupId = upgradeGroupModel.Id;
                        }
                        _context.Set<Members>().Update(memberModel);
                        //增加会员积分记录
                        await _context.Set<MemberPointLog>().AddAsync(new MemberPointLog
                        {
                            UserId = model.UserId,
                            Value = model.Point,
                            Remark = $"获得积分，订单号:{model.OrderNo}"
                        });
                    }
                }
                //新增订单日志
                await _context.Set<OrderLog>().AddAsync(new OrderLog
                {
                    OrderId = model.Id,
                    OrderNo = model.OrderNo,
                    ActionType = ActionType.Complete.ToString(),
                    AddBy = "System",
                    AddTime = DateTime.Now,
                    Remark = $"订单[{model.OrderNo}]自动确认完成"
                });

                //修改订单状态
                model.Status = 5;
            }

            //保存到数据库
            _context.Set<Orders>().UpdateRange(list);
            var result = await this.SaveAsync();
        }

        /// <summary>
        /// 结算订单(计划任务)
        /// </summary>
        public async Task JobSettleAsync(WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            //获取订单配置信息
            var jsonData = await _configService.QueryByTypeAsync(ConfigType.OrderConfig);
            var orderConfig = JsonHelper.ToJson<OrderConfigDto>(jsonData?.JsonData);
            if (orderConfig == null)
            {
                return;
            }
            //检查未结算且已收货，必须过了售后期的订单
            var list = await _context.Set<Orders>().Where(x => x.IsSettle == 0
                && x.Status == 5
                && x.CompleteTime != null
                && DateTime.Compare(x.CompleteTime.Value, DateTime.Now.AddDays(-1 * orderConfig.OrdereSettle)) <= 0)
                .ToListAsync();
            if (list == null || list.Count == 0)
            {
                return;
            }
            //循环处理
            foreach (var model in list)
            {
                //查找商户打款到余额
                if (model.SettleAmount > 0)
                {
                    var merchantModel = await _context.Set<Merchants>().FirstOrDefaultAsync(x => x.Id == model.MerchantId);
                    if (merchantModel != null)
                    {
                        //如果商户交易费百分比如果为零则获取分类的交易百分比
                        var tradeFee = merchantModel.TradeFee;
                        if (tradeFee == 0)
                        {
                            var categoryModel = await _context.Set<MerchantCategory>().FirstOrDefaultAsync(x => x.Id == merchantModel.CategoryId);
                            if (categoryModel != null)
                            {
                                tradeFee = categoryModel.TradeFee;
                            }
                        }
                        //计算交易费
                        decimal tradeFeeAmount = 0;
                        if (tradeFee > 0 && model.SettleAmount > 0)
                        {
                            tradeFeeAmount = Math.Round(model.SettleAmount * (tradeFee / 100M), 2);
                        }
                        //计算获取营业收金额
                        var merchantAmount = model.SettleAmount - tradeFeeAmount;
                        //增加资金日志
                        await _context.Set<MerchantAmountLog>().AddAsync(new MerchantAmountLog
                        {
                            MerchantId = model.MerchantId,
                            Amount = merchantAmount,
                            AddTime = DateTime.Now,
                            Remark = $"结算订单：{model.OrderNo}，营业收入{merchantAmount}元，交易费{tradeFeeAmount}元"
                        });
                        merchantModel.Amount += merchantAmount;
                        _context.Set<Merchants>().Update(merchantModel);
                    }
                }
                //标记为已结算
                model.IsSettle = 1;
            }
            //保存到数据库
            _context.Set<Orders>().UpdateRange(list);
            var result = await this.SaveAsync();
        }

        #region 私有辅助方法=================================
        /// <summary>
        /// 1.新增抢购订单
        /// </summary>
        private async Task<OrderCollection> AddRushOrder(OrdersAddDto modelDto)
        {
            if (_context == null)
            {
                throw new ResponseException("请选连接到数据库");
            }
            //获取订单配置信息
            var jsonData = await _configService.QueryByTypeAsync(ConfigType.OrderConfig);
            var orderConfig = JsonHelper.ToJson<OrderConfigDto>(jsonData?.JsonData);
            if (orderConfig == null)
            {
                throw new ResponseException("找不到系统的订单配置信息");
            }
            //获取会员信息
            var memberModel = await _context.Set<Members>().Include(x => x.User).Include(x => x.Group)
                .FirstOrDefaultAsync(x => x.UserId == modelDto.UserId);
            if (memberModel == null)
            {
                throw new ResponseException($"会员账户不存在或已删除");
            }
            //获取支付方式信息
            var paymentModel = await _context.Set<Payment>().FirstOrDefaultAsync(x => x.Id == modelDto.PaymentId);
            if (paymentModel == null)
            {
                throw new ResponseException($"支付方式不存在或已删除");
            }
            //创建一条收款单与订单关联
            OrderCollection orderCollection = new();
            orderCollection.UserId = memberModel.UserId;
            orderCollection.TradeNo = $"TN{UtilConvert.GetGuidToNumber()}";
            orderCollection.TradeType = 0;
            orderCollection.PaymentId = paymentModel.Id;
            orderCollection.PaymentTitle = paymentModel.Title;
            orderCollection.PaymentCash = paymentModel.ProviderType == 0 ? (byte)1 : (byte)0;
            orderCollection.CollectionType = 0;
            orderCollection.EndTime = DateTime.Now.AddMinutes(orderConfig.OrderExpired);//有效支付时间
            //遍历订单，批量写入
            foreach (var modelt in modelDto.OrderList)
            {
                //映射DTO到实体
                var model = _mapper.Map<Orders>(modelt);
                model.OrderGoods.Clear();//清空订单商品以便重新添加
                //赋值统一的参数值
                model.OrderType = modelDto.OrderType;
                model.UserId = modelDto.UserId.GetValueOrDefault();
                model.UserName = memberModel.User?.UserName;//添加用户名
                model.AcceptName = modelDto.AcceptName;
                model.TelPhone = modelDto.TelPhone;
                model.Mobile = modelDto.Mobile;
                model.Province = modelDto.Province;
                model.City = modelDto.City;
                model.Area = modelDto.Area;
                model.Address = modelDto.Address;
                //如果是线下收款，则将订单更改为待发货状态
                if (paymentModel.ProviderType == 0)
                {
                    model.Status = 2;
                }
                //拼接收货地址
                var addressArr = model.Address?.Split(",");
                if (addressArr?.Length > 0)
                {
                    model.Address = $"{model.Province},{model.City},{model.Area},{addressArr[^1]}";
                }
                //查询配送方式
                var deliveryModel = await _context.Set<ShopDelivery>().Include(x => x.DeliveryAreas)
                    .FirstOrDefaultAsync(x => x.Id == model.DeliveryId && x.IsDelete == 0 && x.Status == 0 && x.MerchantId == modelt.MerchantId);
                if (deliveryModel == null)
                {
                    ////新增抢购订单中的配送方式
                    throw new ResponseException("配送方式有误，请确认后操作");
                }
                //查找抢购详情
                var speedModel = await _context.Set<ShopSpeed>().FirstOrDefaultAsync(
                    x => x.IsDelete == 0
                    && x.Status == 0
                    && x.MerchantId == modelt.MerchantId
                    && DateTime.Compare(x.StartTime, DateTime.Now) <= 0
                    && DateTime.Compare(x.EndTime, DateTime.Now) >= 0
                    && x.Id == modelt.ActiveId);
                if (speedModel == null)
                {
                    throw new ResponseException($"抢购活动{modelt.ActiveId}不存在或已过期");
                }
                //查询商品货品
                var productModel = await _context.Set<ShopGoodsProduct>()
                    .Include(x => x.ShopGoods)
                    .FirstOrDefaultAsync(x => x.Id == speedModel.ProductId && x.ShopGoods.IsDelete == 0 && x.ShopGoods.Status == 0);
                if (productModel == null || productModel.ShopGoods == null)
                {
                    throw new ResponseException("货品不存在或已下架");
                }
                //检查库存数量
                if (productModel.StockQuantity < 1)
                {
                    throw new ResponseException($"商品已抢购完毕");
                }
                //正式赋值给订单货品
                int quantityNum = 1;
                model.OrderGoods.Add(new OrderGoods
                {
                    GoodsId = productModel.GoodsId,
                    ProductId = productModel.Id,
                    GoodsNo = productModel.GoodsNo,
                    GoodsTitle = productModel.ShopGoods.Title,
                    SkuText = productModel.SkuText,
                    ImgUrl = productModel.ImgUrl ?? productModel.ShopGoods.ImgUrl,
                    GoodsPrice = productModel.SellPrice,
                    RealPrice = speedModel.Price,
                    Quantity = quantityNum,
                    Weight = productModel.Weight
                });
                //正式赋值给订单总积分和经验值
                model.Point += productModel.ShopGoods.Point * quantityNum;
                model.Exp += productModel.ShopGoods.Exp * quantityNum;
                //货品及商品减库存，销售增加
                productModel.StockQuantity -= quantityNum;
                productModel.ShopGoods.StockQuantity -= quantityNum;
                productModel.ShopGoods.SaleCount += quantityNum;
                _context.Set<ShopGoodsProduct>().Update(productModel);

                //生成订单号
                model.OrderNo = $"SN{UtilConvert.GetGuidToNumber()}";
                //计算订单应付商品总金额
                model.PayableAmount = model.OrderGoods.Select(x => x.GoodsPrice * x.Quantity).Sum();
                //计算订单实付商品总金额
                model.RealAmount = model.OrderGoods.Select(x => x.RealPrice * x.Quantity).Sum();
                //订单优惠金额=应付商品总金额-实付商品总金额
                model.DiscountAmount = model.PayableAmount - model.RealAmount;
                //应付总运费
                int totalWeight = model.OrderGoods.Select(x => x.Weight * x.Quantity).Sum();//总商品重量(克)
                model.PayableFreight = GetPayableFreightAsync(deliveryModel,
                    model.Province,
                    totalWeight > 1000 ? totalWeight / 1000 : 1,
                    model.IsInsure, model.InsurePrice);
                //实付总运费
                model.RealFreight = model.PayableFreight;
                if (productModel.ShopGoods.IsDeliveryFee == 1)
                {
                    model.RealFreight = 0;//商品免运费
                }
                //订单总金额=实付总运费+应付商品总金额-优惠总金额-订单折扣或涨价
                model.OrderAmount = model.SettleAmount = model.RealFreight + model.PayableAmount - model.PromotionAmount - model.DiscountAmount;

                //统计累加到收款表
                orderCollection.FreightAmount += model.RealFreight;
                orderCollection.DiscountAmount += model.PromotionAmount + model.DiscountAmount;
                orderCollection.PaymentAmount += model.OrderAmount;
                //将订单添加进收款关联表
                orderCollection.CollectionRelations.Add(new OrderCollectionRelation()
                {
                    Order = model
                });
            }
            //保存收款及订单
            await _context.Set<OrderCollection>().AddAsync(orderCollection);
            //一次保存到数据库
            var result = await this.SaveAsync();
            if (!result)
            {
                throw new ResponseException("订单保存时发生意外错误");
            }
            return orderCollection;
        }

        /// <summary>
        /// 2.新增预售订单
        /// </summary>
        private async Task<OrderCollection> AddPresellOrder(OrdersAddDto modelDto)
        {
            if (_context == null)
            {
                throw new ResponseException("请选连接到数据库");
            }
            //获取订单配置信息
            var jsonData = await _configService.QueryByTypeAsync(ConfigType.OrderConfig);
            var orderConfig = JsonHelper.ToJson<OrderConfigDto>(jsonData?.JsonData);
            if (orderConfig == null)
            {
                throw new ResponseException("找不到系统的订单配置信息");
            }
            //获取会员信息
            var memberModel = await _context.Set<Members>().Include(x => x.User).Include(x => x.Group)
                .FirstOrDefaultAsync(x => x.UserId == modelDto.UserId);
            if (memberModel == null)
            {
                throw new ResponseException($"会员账户不存在或已删除");
            }
            //获取支付方式信息
            var paymentModel = await _context.Set<Payment>().FirstOrDefaultAsync(x => x.Id == modelDto.PaymentId);
            if (paymentModel == null)
            {
                throw new ResponseException($"支付方式不存在或已删除");
            }
            //创建一条收款单与订单关联
            OrderCollection orderCollection = new();
            orderCollection.UserId = memberModel.UserId;
            orderCollection.TradeNo = $"TN{UtilConvert.GetGuidToNumber()}";
            orderCollection.PaymentId = paymentModel.Id;
            orderCollection.PaymentTitle = paymentModel.Title;
            orderCollection.CollectionType = 1;
            orderCollection.PaymentCash = paymentModel.ProviderType == 0 ? (byte)1 : (byte)0;
            orderCollection.EndTime = DateTime.Now.AddMinutes(orderConfig.OrderExpired);//有效支付时间
            //创建尾款收款单与订单关联列表
            List<OrderCollection> orderCollectionList = new();
            //遍历订单，批量写入
            foreach (var modelt in modelDto.OrderList)
            {
                //映射DTO到实体
                var model = _mapper.Map<Orders>(modelt);
                model.OrderGoods.Clear();//清空订单商品以便重新添加
                //赋值统一的参数值
                model.OrderType = modelDto.OrderType;
                model.UserId = modelDto.UserId.GetValueOrDefault();
                model.UserName = memberModel.User?.UserName;//添加用户名
                model.AcceptName = modelDto.AcceptName;
                model.TelPhone = modelDto.TelPhone;
                model.Mobile = modelDto.Mobile;
                model.Province = modelDto.Province;
                model.City = modelDto.City;
                model.Area = modelDto.Area;
                model.Address = modelDto.Address;
                //如果是线下收款，则将订单更改为待发货状态
                if (paymentModel.ProviderType == 0)
                {
                    model.Status = 2;
                }
                //拼接收货地址
                var addressArr = model.Address?.Split(",");
                if (addressArr?.Length > 0)
                {
                    model.Address = $"{model.Province},{model.City},{model.Area},{addressArr[^1]}";
                }
                //查询配送方式
                var deliveryModel = await _context.Set<ShopDelivery>().Include(x => x.DeliveryAreas)
                    .FirstOrDefaultAsync(x => x.Id == model.DeliveryId && x.IsDelete == 0 && x.Status == 0 && x.MerchantId == modelt.MerchantId);
                if (deliveryModel == null)
                {
                    //新增预售订单中的配送方式
                    throw new ResponseException("配送方式有误，请确认后操作");
                }
                //查找预售详情
                var presellModel = await _context.Set<ShopPresell>().FirstOrDefaultAsync(
                    x => x.IsDelete == 0
                    && x.Status == 0
                    && x.MerchantId == modelt.MerchantId
                    && DateTime.Compare(x.ActStartTime, DateTime.Now) <= 0
                    && DateTime.Compare(x.ActEndTime, DateTime.Now) >= 0
                    && x.Id == modelt.ActiveId);
                if (presellModel == null)
                {
                    throw new ResponseException($"预售活动{modelt.ActiveId}不存在或已过期");
                }
                //查询商品货品
                var productModel = await _context.Set<ShopGoodsProduct>()
                    .Include(x => x.ShopGoods)
                    .FirstOrDefaultAsync(x => x.Id == presellModel.ProductId && x.ShopGoods.Status == 0);
                if (productModel == null || productModel.ShopGoods == null)
                {
                    throw new ResponseException("货品不存在或已下架");
                }
                //检查库存数量
                if (productModel.StockQuantity < 1)
                {
                    throw new ResponseException($"商品已售空，请检查重试");
                }
                //正式赋值给订单货品
                int quantityNum = 1;
                model.OrderGoods.Add(new OrderGoods
                {
                    GoodsId = productModel.GoodsId,
                    ProductId = productModel.Id,
                    GoodsNo = productModel.GoodsNo,
                    GoodsTitle = productModel.ShopGoods.Title,
                    SkuText = productModel.SkuText,
                    ImgUrl = productModel.ImgUrl ?? productModel.ShopGoods.ImgUrl,
                    GoodsPrice = productModel.SellPrice,
                    RealPrice = presellModel.TotalPrice,
                    Quantity = quantityNum,
                    Weight = productModel.Weight
                });
                //正式赋值给订单总积分和经验值
                model.Point += productModel.ShopGoods.Point * quantityNum;
                model.Exp += productModel.ShopGoods.Exp * quantityNum;
                //货品及商品减库存，销售增加
                productModel.StockQuantity -= quantityNum;
                productModel.ShopGoods.StockQuantity -= quantityNum;
                productModel.ShopGoods.SaleCount += quantityNum;
                _context.Set<ShopGoodsProduct>().Update(productModel);

                //生成订单号
                model.OrderNo = $"LN{UtilConvert.GetGuidToNumber()}";
                model.RetainStartTime = presellModel.PayStartTime;
                model.RetainEndTime = presellModel.PayEndTime;
                //计算订单应付商品总金额
                model.PayableAmount = model.OrderGoods.Select(x => x.GoodsPrice * x.Quantity).Sum();
                //计算订单实付商品总金额
                model.RealAmount = model.OrderGoods.Select(x => x.RealPrice * x.Quantity).Sum();
                //订单优惠金额=应付商品总金额-实付商品总金额
                model.DiscountAmount = model.PayableAmount - model.RealAmount;
                //应付总运费
                int totalWeight = model.OrderGoods.Select(x => x.Weight * x.Quantity).Sum();//总商品重量(克)
                model.PayableFreight = GetPayableFreightAsync(deliveryModel,
                    model.Province,
                    totalWeight > 1000 ? totalWeight / 1000 : 1,
                    model.IsInsure, model.InsurePrice);
                //实付总运费
                model.RealFreight = model.PayableFreight;
                if (productModel.ShopGoods.IsDeliveryFee == 1)
                {
                    model.RealFreight = 0;//商品免运费
                }
                //订单总金额=实付总运费+应付商品总金额-促销活动金额-优惠券金额-订单折扣或涨价
                model.OrderAmount = model.SettleAmount = model.RealFreight + model.PayableAmount - model.PromotionAmount - model.CouponAmount - model.DiscountAmount;
                //预付款金额
                model.FrontAmount = presellModel.FrontAmount;

                //统计累加到收款表
                orderCollection.FreightAmount += model.RealFreight;
                orderCollection.DiscountAmount += model.DiscountAmount;
                orderCollection.PaymentAmount += model.FrontAmount;
                //将订单添加预付款收款关联
                orderCollection.CollectionRelations.Add(new OrderCollectionRelation()
                {
                    Order = model
                });
                //将订单添加进尾款收款关联
                orderCollectionList.Add(new OrderCollection
                {
                    TradeNo = $"TN{UtilConvert.GetGuidToNumber()}",
                    TradeType = 0,
                    PaymentId = paymentModel.Id,
                    PaymentTitle = paymentModel.Title,
                    CollectionType = 2,
                    PaymentCash = paymentModel.ProviderType == 0 ? (byte)1 : (byte)0,
                    FreightAmount = model.RealFreight,
                    DiscountAmount = model.DiscountAmount,
                    PaymentAmount = model.OrderAmount - model.FrontAmount,
                    StartTime = presellModel.PayStartTime,
                    EndTime = presellModel.PayEndTime,
                    CollectionRelations = new List<OrderCollectionRelation>{
                        new OrderCollectionRelation {
                            Order = model
                        }
                    }

                });
            }
            //添加预付款收款及订单
            await _context.Set<OrderCollection>().AddAsync(orderCollection);
            //开启事务
            using (var transaction = await _context.Database.BeginTransactionAsync())
            {
                try
                {
                    //先保存之前的修改，让订单先写入数据库
                    await this.SaveAsync();
                    //再添加尾款收款记录与订单关联
                    await _context.Set<OrderCollection>().AddRangeAsync(orderCollectionList);
                    //再次保存到数据库
                    await this.SaveAsync();
                    //提交事务
                    await transaction.CommitAsync();
                }
                catch
                {
                    //回滚事务
                    await transaction.RollbackAsync();
                    throw new ResponseException("订单保存时发生意外错误");
                }
            }
            return orderCollection;
        }

        /// <summary>
        /// 3.新增积分兑换订单
        /// </summary>
        private async Task<OrderCollection> AddPointOrder(OrdersAddDto modelDto)
        {
            if (_context == null)
            {
                throw new ResponseException("请选连接到数据库");
            }
            //获取订单配置信息
            var jsonData = await _configService.QueryByTypeAsync(ConfigType.OrderConfig);
            var orderConfig = JsonHelper.ToJson<OrderConfigDto>(jsonData?.JsonData);
            if (orderConfig == null)
            {
                throw new ResponseException("找不到系统的订单配置信息");
            }
            //获取会员信息
            var memberModel = await _context.Set<Members>().Include(x => x.User).Include(x => x.Group)
                .FirstOrDefaultAsync(x => x.UserId == modelDto.UserId);
            if (memberModel == null)
            {
                throw new ResponseException($"会员账户不存在或已删除");
            }
            //获取支付方式信息
            var paymentModel = await _context.Set<Payment>().FirstOrDefaultAsync(x => x.Id == modelDto.PaymentId);
            if (paymentModel == null)
            {
                throw new ResponseException($"支付方式不存在或已删除");
            }
            //会员积分记录列表
            List<MemberPointLog> pointLogList = new();
            //创建一条收款单与订单关联
            OrderCollection orderCollection = new();
            orderCollection.UserId = memberModel.UserId;
            orderCollection.TradeNo = $"TN{UtilConvert.GetGuidToNumber()}";
            orderCollection.TradeType = 0;
            orderCollection.PaymentId = paymentModel.Id;
            orderCollection.PaymentTitle = paymentModel.Title;
            orderCollection.PaymentCash = paymentModel.ProviderType == 0 ? (byte)1 : (byte)0;
            orderCollection.CollectionType = 0;
            orderCollection.EndTime = DateTime.Now.AddMinutes(orderConfig.OrderExpired);//有效支付时间
            //遍历订单，批量写入
            foreach (var modelt in modelDto.OrderList)
            {
                //映射DTO到实体
                var model = _mapper.Map<Orders>(modelt);
                model.OrderGoods.Clear();//清空订单商品以便重新添加
                //赋值统一的参数值
                model.OrderType = modelDto.OrderType;
                model.UserId = modelDto.UserId.GetValueOrDefault();
                model.UserName = memberModel.User?.UserName;//添加用户名
                model.AcceptName = modelDto.AcceptName;
                model.TelPhone = modelDto.TelPhone;
                model.Mobile = modelDto.Mobile;
                model.Province = modelDto.Province;
                model.City = modelDto.City;
                model.Area = modelDto.Area;
                model.Address = modelDto.Address;
                //如果是线下收款，则将订单更改为待发货状态
                if (paymentModel.ProviderType == 0)
                {
                    model.Status = 2;
                }
                //拼接收货地址
                var addressArr = model.Address?.Split(",");
                if (addressArr?.Length > 0)
                {
                    model.Address = $"{model.Province},{model.City},{model.Area},{addressArr[^1]}";
                }
                //查询配送方式
                var deliveryModel = await _context.Set<ShopDelivery>().Include(x => x.DeliveryAreas)
                    .FirstOrDefaultAsync(x => x.Id == model.DeliveryId && x.IsDelete == 0 && x.Status == 0 && x.MerchantId == modelt.MerchantId);
                if (deliveryModel == null)
                {
                    //新增积分兑换订单配送方式
                    throw new ResponseException("配送方式有误，请确认后操作");
                }
                //查找积分换购详情
                var pointModel = await _context.Set<ShopConvert>().FirstOrDefaultAsync(
                    x => x.IsDelete == 0
                    && x.Status == 0
                    && x.MerchantId == modelt.MerchantId
                    && x.Id == modelt.ActiveId);
                if (pointModel == null)
                {
                    throw new ResponseException($"积分兑换{modelt.ActiveId}不存在或已失败");
                }
                //检查会员账户积分是否能抵扣
                if (memberModel.Point < pointModel.Point)
                {
                    throw new ResponseException($"会员账户积分不足，无法兑换");
                }
                //查询货品信息
                var productModel = await _context.Set<ShopGoodsProduct>()
                    .Include(x => x.ShopGoods)
                    .FirstOrDefaultAsync(x => x.Id == pointModel.ProductId && x.ShopGoods.IsDelete == 0 && x.ShopGoods.Status == 0);
                if (productModel?.ShopGoods == null)
                {
                    throw new ResponseException("商品不存在或已下架");
                }
                //检查库存数量
                int quantityNum = 1;
                if (productModel.StockQuantity < quantityNum)
                {
                    throw new ResponseException($"商品{productModel.GoodsId}库存不足");
                }
                //正式赋值给订单货品
                model.OrderGoods.Add(new OrderGoods
                {
                    GoodsId = productModel.GoodsId,
                    ProductId = productModel.Id,
                    GoodsNo = productModel.GoodsNo,
                    GoodsTitle = productModel.ShopGoods?.Title,
                    SkuText = productModel.SkuText,
                    ImgUrl = productModel.ImgUrl ?? productModel.ShopGoods?.ImgUrl,
                    GoodsPrice = productModel.SellPrice,
                    RealPrice = 0,
                    Quantity = quantityNum,
                    Weight = productModel.Weight
                });
                //正式赋值给订单总积分和经验值(累加)
                model.Point += -pointModel.Point * quantityNum;
                model.Exp += productModel.ShopGoods?.Exp ?? 0 * quantityNum;
                //货品及商品减库存，销售增加
                productModel.StockQuantity -= quantityNum;
                productModel.ShopGoods!.StockQuantity -= quantityNum;
                productModel.ShopGoods!.SaleCount += quantityNum;
                //修改商品库存
                _context.Set<ShopGoodsProduct>().Update(productModel);

                //生成订单号
                model.OrderNo = $"PN{UtilConvert.GetGuidToNumber()}";
                //订单应付商品总金额
                model.PayableAmount = model.OrderGoods.Select(x => x.GoodsPrice * x.Quantity).Sum();
                //订单实付商品总金额
                model.RealAmount = 0;
                //应付总运费
                int totalWeight = model.OrderGoods.Select(x => x.Weight * x.Quantity).Sum();//总商品重量(克)
                model.PayableFreight = GetPayableFreightAsync(deliveryModel,
                    model.Province,
                    totalWeight > 1000 ? totalWeight / 1000 : 1,
                    model.IsInsure, model.InsurePrice);
                //实付总运费
                model.RealFreight = model.PayableFreight;
                if (productModel.ShopGoods.IsDeliveryFee == 1)
                {
                    model.RealFreight = 0;
                }
                //订单优惠金额=应付商品总金额-实付商品总金额
                model.DiscountAmount = model.PayableAmount - model.RealAmount;
                //订单总金额=实付总运费+应付商品总金额-促销活动金额-优惠券金额-订单折扣或涨价
                model.OrderAmount = model.SettleAmount = model.RealFreight + model.PayableAmount - model.PromotionAmount - model.CouponAmount - model.DiscountAmount;
                //如果订单金额为零则设置已支付
                if (model.OrderAmount == 0)
                {
                    model.Status = 2;
                    model.PaymentStatus = 2;
                    model.PaymentTime = DateTime.Now;
                }
                //统计累加到收款表
                orderCollection.FreightAmount += model.RealFreight;
                orderCollection.DiscountAmount += model.PromotionAmount + model.CouponAmount + model.DiscountAmount;
                orderCollection.PaymentAmount += model.OrderAmount;
                //将订单添加进收款关联表
                orderCollection.CollectionRelations.Add(new OrderCollectionRelation()
                {
                    Order = model
                });
                //将积分记录添加到列表
                pointLogList.Add(new MemberPointLog
                {
                    UserId = model.UserId,
                    Value = pointModel.Point * -1,
                    Remark = $"兑换商品，订单号:{model.OrderNo}"
                });
                //扣减会员账户积分
                memberModel.Point -= pointModel.Point;
            }
            //如果收款金额为零则设置为已收款状态
            if (orderCollection.PaymentAmount == 0)
            {
                orderCollection.Status = 2;
                orderCollection.CompleteTime = DateTime.Now;
            }
            //增加会员积分记录
            await _context.Set<MemberPointLog>().AddRangeAsync(pointLogList);
            //修改会员信息
            _context.Set<Members>().Update(memberModel);
            //保存收款及订单
            await _context.Set<OrderCollection>().AddAsync(orderCollection);
            //开启事务
            using (var transaction = await _context.Database.BeginTransactionAsync())
            {
                try
                {
                    //先保存之前的修改
                    await this.SaveAsync();
                    //创建积分兑换记录列表
                    List<ShopConvertHistory> convertHistoryList = new();
                    foreach (var item in orderCollection.CollectionRelations)
                    {
                        if (item.Order != null)
                        {
                            convertHistoryList.Add(new ShopConvertHistory
                            {
                                ConvertId = item.Order.ActiveId,
                                UserId = item.Order.UserId,
                                UserName = item.Order.UserName,
                                OrderId = item.Order.Id,
                                Status = 1
                            });
                        }
                    }
                    //保存积分兑换记录
                    await _context.Set<ShopConvertHistory>().AddRangeAsync(convertHistoryList);
                    //再次保存到数据库
                    await this.SaveAsync();
                    //提交事务
                    await transaction.CommitAsync();
                }
                catch
                {
                    //回滚事务
                    await transaction.RollbackAsync();
                    throw new ResponseException("订单保存时发生意外错误");
                }
            }
            return orderCollection;
        }

        /// <summary>
        /// 0.新增普通订单
        /// </summary>
        private async Task<OrderCollection> AddNormalOrder(OrdersAddDto modelDto)
        {
            if (_context == null)
            {
                throw new ResponseException("请选连接到数据库");
            }
            //获取订单配置信息
            var jsonData = await _configService.QueryByTypeAsync(ConfigType.OrderConfig);
            var orderConfig = JsonHelper.ToJson<OrderConfigDto>(jsonData?.JsonData);
            if (orderConfig == null)
            {
                throw new ResponseException("找不到系统的订单配置信息");
            }
            //获取会员信息
            var memberModel = await _context.Set<Members>().Include(x => x.User).Include(x => x.Group)
                .FirstOrDefaultAsync(x => x.UserId == modelDto.UserId);
            if (memberModel == null)
            {
                throw new ResponseException($"会员账户不存在或已删除");
            }
            //获取支付方式信息
            var paymentModel = await _context.Set<Payment>().FirstOrDefaultAsync(x => x.Id == modelDto.PaymentId);
            if (paymentModel == null)
            {
                throw new ResponseException($"支付方式不存在或已删除");
            }
            //创建一条收款单与订单关联
            OrderCollection orderCollection = new();
            orderCollection.UserId = memberModel.UserId;
            orderCollection.TradeNo= $"TN{UtilConvert.GetGuidToNumber()}";
            orderCollection.TradeType = 0;
            orderCollection.PaymentId = paymentModel.Id;
            orderCollection.PaymentTitle = paymentModel.Title;
            orderCollection.PaymentCash = paymentModel.ProviderType == 0 ? (byte)1 : (byte)0;
            orderCollection.CollectionType = 0;
            orderCollection.EndTime = DateTime.Now.AddMinutes(orderConfig.OrderExpired);//有效支付时间
            //遍历订单，批量写入
            foreach (var modelt in modelDto.OrderList)
            {
                //映射DTO到实体
                var model = _mapper.Map<Orders>(modelt);
                model.OrderGoods.Clear();//清空订单商品以便重新添加
                //赋值统一的参数值
                model.OrderType = modelDto.OrderType;
                model.UserId = modelDto.UserId.GetValueOrDefault();
                model.UserName= memberModel.User?.UserName;//添加用户名
                model.AcceptName = modelDto.AcceptName;
                model.TelPhone = modelDto.TelPhone;
                model.Mobile = modelDto.Mobile;
                model.Province = modelDto.Province;
                model.City = modelDto.City;
                model.Area = modelDto.Area;
                model.Address = modelDto.Address;
                //如果是线下收款，则将订单更改为待发货状态
                if (paymentModel.ProviderType == 0)
                {
                    model.Status = 2;
                }
                //拼接收货地址
                var addressArr = model.Address?.Split(",");
                if (addressArr?.Length > 0)
                {
                    model.Address = $"{model.Province},{model.City},{model.Area},{addressArr[^1]}";
                }
                //查询配送方式
                var deliveryModel = await _context.Set<ShopDelivery>().Include(x => x.DeliveryAreas)
                    .FirstOrDefaultAsync(x => x.Id == model.DeliveryId && x.IsDelete == 0 && x.Status == 0 && x.MerchantId == modelt.MerchantId);
                if (deliveryModel == null)
                {
                    //新增普通订单配送方式
                    throw new ResponseException("配送方式有误，请确认后操作");
                }
                //查询商品货品列表
                var productIds = modelt.OrderGoods.Select(x => x.ProductId);//货品列表
                var productList = await _context.Set<ShopGoodsProduct>()
                    .Include(x => x.ShopGoods).ThenInclude(x => x!.CategoryRelations)
                    .Include(x => x.GroupPrices)
                    .Where(x => x.ShopGoods != null && x.ShopGoods.IsDelete == 0 && x.ShopGoods.Status == 0 && productIds.Contains(x.Id)).ToListAsync();
                if (productList == null)
                {
                    throw new ResponseException("商品不存在或已下架");
                }
                //检查是否全部免运费
                bool isDeliveryFee = true;
                //遍历商品货品列表
                foreach (var product in productList)
                {
                    if (product.ShopGoods == null)
                    {
                        continue;
                    }
                    //如果有任何一件不是免运费，则需要收取运费
                    if (product.ShopGoods.IsDeliveryFee == 0)
                    {
                        isDeliveryFee = false;
                    }
                    //查询会员组价格
                    int discount = memberModel.Group?.Discount ?? 100;
                    var groupPrice = product.GroupPrices.FirstOrDefault(x => x.GroupId == memberModel.GroupId);
                    //取得DTO对应货品的购买数量
                    var dtoOrderGoods = modelt.OrderGoods.FirstOrDefault(x => x.ProductId == product.Id);
                    var quantityNum = dtoOrderGoods != null ? dtoOrderGoods.Quantity : 0;
                    //检查最少购买数量
                    if (quantityNum < product.MinQuantity)
                    {
                        throw new ResponseException($"该商品至少购买{product.MinQuantity}件");
                    }
                    //检查库存数量
                    if (product.StockQuantity < quantityNum)
                    {
                        throw new ResponseException($"商品{product.GoodsId}库存不足");
                    }
                    //正式赋值给订单货品
                    model.OrderGoods.Add(new OrderGoods
                    {
                        GoodsId = product.GoodsId,
                        ProductId = product.Id,
                        GoodsNo = product.GoodsNo,
                        GoodsTitle = product.ShopGoods.Title,
                        SkuText = product.SkuText,
                        ImgUrl = product.ImgUrl ?? product.ShopGoods.ImgUrl,
                        GoodsPrice = product.SellPrice,
                        RealPrice = groupPrice != null ? groupPrice.Price : product.SellPrice * ((decimal)discount / 100),
                        Quantity = quantityNum,
                        Weight = product.Weight
                    });
                    //正式赋值给订单总积分和经验值(累加)
                    model.Point += product.ShopGoods.Point * quantityNum;
                    model.Exp += product.ShopGoods.Exp * quantityNum;
                    //货品及商品减库存，销售增加
                    product.StockQuantity -= quantityNum;
                    product.ShopGoods.StockQuantity -= quantityNum;
                    product.ShopGoods.SaleCount += quantityNum;
                    _context.Set<ShopGoodsProduct>().Update(product);
                }
                //生成订单号
                model.OrderNo = $"BN{UtilConvert.GetGuidToNumber()}";
                //计算订单应付商品总金额
                model.PayableAmount = model.OrderGoods.Select(x => x.GoodsPrice * x.Quantity).Sum();
                //计算订单实付商品总金额
                model.RealAmount = model.OrderGoods.Select(x => x.RealPrice * x.Quantity).Sum();
                //订单优惠金额=应付商品总金额-实付商品总金额
                model.DiscountAmount = model.PayableAmount - model.RealAmount;
                //应付总运费
                int totalWeight = model.OrderGoods.Select(x => x.Weight * x.Quantity).Sum();//总商品重量(克)
                model.PayableFreight = GetPayableFreightAsync(deliveryModel,
                    model.Province,
                    totalWeight > 1000 ? totalWeight / 1000 : 1,
                    model.IsInsure, model.InsurePrice);
                //实付总运费
                model.RealFreight = model.PayableFreight;
                if (isDeliveryFee)
                {
                    model.RealFreight = 0;//所有的商品都是免运费
                }
                //获取会员优惠券
                if (modelt.UseCouponId > 0)
                {
                    //查询优惠券信息
                    var useCouponModel = await _context.Set<ShopCouponHistory>()
                        .Include(x => x.ShopCoupon).ThenInclude(x => x.GoodsRelations)
                        .FirstOrDefaultAsync(x =>
                            x.Id == modelt.UseCouponId
                            && x.Status == 0
                            && x.IsUse == 0
                            && x.UserId == model.UserId
                            && x.ShopCoupon != null
                            && x.ShopCoupon.MerchantId == modelt.MerchantId
                            && x.ShopCoupon.IsDelete == 0
                            && DateTime.Compare(x.ShopCoupon.StartTime, DateTime.Now) <= 0
                            && DateTime.Compare(x.ShopCoupon.EndTime, DateTime.Now) >= 0);
                    if (useCouponModel == null || useCouponModel.ShopCoupon == null)
                    {
                        throw new ResponseException($"优惠券[{modelt.UseCouponId}]不存在或已失效");
                    }
                    //检查优惠券是否可用
                    //0店铺券，需满足消费金额
                    if (useCouponModel.ShopCoupon.UseType == 0)
                    {
                        if(useCouponModel.ShopCoupon.MinAmount > 0 && model.OrderGoods.Select(x => x.GoodsPrice * x.Quantity).Sum() < useCouponModel.ShopCoupon.MinAmount)
                        {
                            throw new ResponseException($"优惠券不可用，请检查重试");
                        }
                    }
                    //1商品券，需满足消费金额及对应的商品
                    else if (useCouponModel.ShopCoupon.UseType == 1)
                    {
                        //取出优惠券可用商品ID
                        var couponGoodsIds = useCouponModel.ShopCoupon.GoodsRelations.Select(x => x.GoodsId);
                        //查找符合条件的商品
                        var orderGoodsIds = model.OrderGoods.Where(x => couponGoodsIds.Contains(x.GoodsId)).ToList();
                        if (orderGoodsIds == null || orderGoodsIds.Select(x => x.GoodsPrice * x.Quantity).Sum() < useCouponModel.ShopCoupon.MinAmount)
                        {
                            throw new ResponseException($"优惠券不可用，请检查重试");
                        }
                    }
                    //修改订单中的优惠金额
                    model.CouponAmount = useCouponModel.ShopCoupon.Amount;
                    //修改可用优惠券的状态
                    useCouponModel.OrderNo = model.OrderNo;
                    useCouponModel.IsUse = 1;
                    useCouponModel.Status = 1;
                    useCouponModel.UseTime = DateTime.Now;
                    useCouponModel.ShopCoupon.UseCount += 1;
                    _context.Set<ShopCouponHistory>().Update(useCouponModel);
                }
                //获取促销活动
                var promotionModel = await _context.Set<ShopPromotion>().FirstOrDefaultAsync(
                    x => x.IsDelete == 0
                    && x.Status == 0
                    && x.MerchantId == modelt.MerchantId
                    && DateTime.Compare(x.StartTime, DateTime.Now) <= 0
                    && DateTime.Compare(x.EndTime, DateTime.Now) >= 0);
                if (promotionModel != null && model.RealAmount > promotionModel.Condition)
                {
                    //奖励阶梯满减
                    if (promotionModel.AwardType == 1)
                    {
                        //计算阶梯满减倍数
                        var discountNum = (int)(model.RealAmount / promotionModel.Condition);
                        //阶梯满减金额=阶梯满减倍数*满减金额
                        var discountAmount = discountNum * promotionModel.AwardValue;
                        //优惠总金额=原优惠金额+阶梯满减金额
                        model.PromotionAmount += discountAmount;
                    }
                    //奖励折扣
                    else if (promotionModel.AwardType == 2)
                    {
                        if (promotionModel.AwardValue < 1 || promotionModel.AwardValue > 100)
                        {
                            throw new ResponseException($"活动{promotionModel.Id}折扣设置有误");
                        }
                        //折扣金额=原实付*折扣
                        var discountAmount = model.RealAmount * ((decimal)promotionModel.AwardValue / 100);
                        discountAmount = Math.Round(model.RealAmount - discountAmount);
                        //优惠总金额=原优惠金额+折扣金额
                        model.PromotionAmount += discountAmount;
                    }
                    //赠送积分
                    else if (promotionModel.AwardType == 3)
                    {
                        model.Point += Convert.ToInt32(promotionModel.AwardValue);
                    }
                    //赠送赠品
                    else if (promotionModel.AwardType == 5)
                    {
                        //查询赠品商品货品
                        var productModel = await _context.Set<ShopGoodsProduct>()
                            .Include(x => x.ShopGoods)
                            .FirstOrDefaultAsync(x => x.Id == promotionModel.AwardValue && x.ShopGoods!.Status == 0);
                        if (productModel != null)
                        {
                            model.OrderGoods.Add(new OrderGoods
                            {
                                GoodsId = productModel.GoodsId,
                                ProductId = productModel.Id,
                                GoodsNo = productModel.GoodsNo,
                                GoodsTitle = $"{productModel.ShopGoods?.Title}[赠品]",
                                SkuText = productModel.SkuText,
                                ImgUrl = productModel.ImgUrl != null ? productModel.ImgUrl : productModel.ShopGoods?.ImgUrl,
                                GoodsPrice = 0,
                                RealPrice = 0,
                                Quantity = 1,
                                Weight = 0
                            });
                        }
                    }
                    //免运费
                    else if (promotionModel.AwardType == 6)
                    {
                        model.RealFreight = 0;
                    }
                    //赋值订单参与的促销活动
                    model.ActiveId = promotionModel.Id;
                }
                //订单总金额=实付总运费+应付商品总金额-促销活动金额-优惠券金额-订单折扣或涨价
                model.OrderAmount = model.SettleAmount = model.RealFreight + model.PayableAmount - model.PromotionAmount - model.CouponAmount - model.DiscountAmount;

                //统计累加到收款表
                orderCollection.FreightAmount += model.RealFreight;
                orderCollection.DiscountAmount += model.PromotionAmount + model.CouponAmount + model.DiscountAmount;
                orderCollection.PaymentAmount += model.OrderAmount;
                //将订单添加进收款关联表
                orderCollection.CollectionRelations.Add(new OrderCollectionRelation()
                {
                    Order = model
                });
                //删除购物车对应的货品
                var cartList = await _context.Set<ShopCart>().Where(x => x.UserId == modelDto.UserId && productIds.Contains(x.ProductId)).ToListAsync();
                _context.Set<ShopCart>().RemoveRange(cartList);
            }

            //保存收款及订单
            await _context.Set<OrderCollection>().AddAsync(orderCollection);
            //一次保存到数据库
            var result = await this.SaveAsync();
            if (!result)
            {
                throw new ResponseException("订单保存时发生意外错误");
            }
            return orderCollection;
        }

        /// <summary>
        /// 完成订单
        /// </summary>
        private async Task<bool> CompleteOrderAsync(Expression<Func<Orders, bool>> funcWhere)
        {
            if (_context == null)
            {
                throw new ResponseException("请选连接到数据库");
            }
            //根据ID获取记录
            var model = await _context.Set<Orders>()
                .Include(x => x.CollectionRelations).ThenInclude(x => x.Collection)
                .FirstOrDefaultAsync(funcWhere);
            //如果不存在则抛出异常
            if (model == null)
            {
                throw new ResponseException("订单不存在或已删除");
            }
            if (model.Status > 4)
            {
                throw new ResponseException("订单已完成，无法操作");
            }
            if (model.DeliveryStatus != 1)
            {
                throw new ResponseException("订单未发货，无法操作");
            }
            //检查支付状态，如果是未付款，则检查是否到付
            if(model.PaymentStatus != 2)
            {
                foreach (var relation in model.CollectionRelations)
                {
                    if (relation.Collection == null)
                    {
                        throw new ResponseException("找不到收款记录，无法操作");
                    }
                    if (relation.Collection.PaymentCash == 0 && relation.Collection.Status != 2)
                    {
                        throw new ResponseException("订单未付款，无法操作");
                    }
                    //货到付款，则修改成已支付
                    if(relation.Collection.PaymentCash == 1)
                    {
                        relation.Collection.Status = 2;
                        relation.Collection.CompleteTime = DateTime.Now;
                    }
                }
                //付款没问题后设置订单付款状态为全部支付
                model.PaymentStatus = 2;
            }
            //检查订单促销活动
            if (model.OrderType == 0 && model.ActiveId > 0)
            {
                //查询促销活动详情
                var promotionModel = await _context.Set<ShopPromotion>()
                    .FirstOrDefaultAsync(x => x.Id == model.ActiveId);
                //赠送优惠券
                if (promotionModel != null && promotionModel.AwardType == 4)
                {
                    if (await _context.Set<ShopCoupon>().FirstOrDefaultAsync(x => x.Id == promotionModel.AwardValue) != null)
                    {
                        await _context.Set<ShopCouponHistory>().AddAsync(new ShopCouponHistory()
                        {
                            CouponId = promotionModel.AwardValue,
                            UserId = model.UserId,
                            UserName = model.UserName,
                            Type = 0,
                            IsUse = 0,
                            Status = 0,
                            AddTime = DateTime.Now
                        });
                    }
                }
            }
            //会员增加积分及经验值
            if (model.Point > 0)
            {
                var memberModel = await _context.Set<Members>().Include(x => x.Group).FirstOrDefaultAsync(x => x.UserId == model.UserId);
                if(memberModel != null)
                {
                    memberModel.Point += model.Point;
                    memberModel.Exp += model.Exp;
                    //检查有无可升级的会员组
                    var upgradeGroupModel = await _context.Set<MemberGroup>().FirstOrDefaultAsync(
                        x => x.Id != memberModel.GroupId
                        && x.IsUpgrade == 1
                        && x.MinExp <= memberModel.Exp
                        && x.MaxExp >= memberModel.Exp);
                    if (upgradeGroupModel != null && upgradeGroupModel.Amount >= memberModel.Group?.Amount)
                    {
                        memberModel.GroupId = upgradeGroupModel.Id;
                    }
                    _context.Set<Members>().Update(memberModel);
                    //增加会员积分记录
                    await _context.Set<MemberPointLog>().AddAsync(new MemberPointLog
                    {
                        UserId = model.UserId,
                        Value = model.Point,
                        Remark = $"获得积分，订单号:{model.OrderNo}"
                    });
                }
            }
            //新增订单日志
            await _context.Set<OrderLog>().AddAsync(new OrderLog
            {
                OrderId = model.Id,
                OrderNo = model.OrderNo,
                ActionType = ActionType.Complete.ToString(),
                AddBy = await _userService.GetUserNameAsync(),
                AddTime = DateTime.Now,
                Remark = $"订单[{model.OrderNo}]确认完成"
            });
            //修改订单状态
            model.Status = 5;
            _context.Set<Orders>().Update(model);

            return await this.SaveAsync();
        }

        /// <summary>
        /// 计算配送价格
        /// </summary>
        /// <param name="model">配送方式实体</param>
        /// <param name="province">省份</param>
        /// <param name="totalWeight">总重量(千克)</param>
        /// <param name="isInsure">是否保价</param>
        /// <param name="insurePrice">保价金额</param>
        private decimal GetPayableFreightAsync(ShopDelivery model, string? province, int totalWeight, int isInsure, decimal insurePrice)
        {
            if (model.IsInsure == 0 && isInsure > 0)
            {
                throw new ResponseException("当前配送方式不支持保价");
            }
            //重量为0时直接返回首重费用
            if (totalWeight == 0)
            {
                return model.FirstPrice;
            }
            //计算配送费用
            decimal firstPrice = model.FirstPrice;//首重费用
            decimal secondPrice = model.SecondPrice;//续重费用
            decimal totalSecondPrice = 0;//续重总费用
            //如果符合自定义地区，采用地区费用
            var areaModel = model.DeliveryAreas.FirstOrDefault(x => x.Province == province);
            if (areaModel != null)
            {
                firstPrice = areaModel.FirstPrice;
                secondPrice = areaModel.SecondPrice;
            }
            //如果总重量大于首重才计算续重费用
            if (totalWeight > model.FirstWeight)
            {
                //续重重量=总重量-首重量
                decimal secondWeight = totalWeight - model.FirstWeight;
                //向上取整，只要有小数都加1
                //续重费用=(续重重量/续重量)*续重价格
                totalSecondPrice = Math.Ceiling(secondWeight / model.SecondWeight) * secondPrice;
            }
            //保价费用=保价金额*保价费率
            decimal insureFreight = 0;
            if (isInsure > 0)
            {
                insureFreight = insurePrice * ((decimal)model.InsureRate / 1000);
                if (insureFreight < model.InsurePrice)
                {
                    insureFreight = model.InsurePrice;//最低保价
                }
            }
            //总运费=首重费用+续重费用+保价费用
            return firstPrice + totalSecondPrice + insureFreight;
        }

        #endregion
    }
}